<template>
  <Atable :tableData="fileList" :tableModel="fileConfig">
    <template #actions="{ row, index }">
      <BtnUpload
          v-model="fileList[index].file"
          class="btn-upload"
          businessTable="StuffInfo"
          :businessId="applyId"
          :subType="row.ruleName"
          :accept="'.pdf,.jpg,.png,.jpeg'"
          :disabled="true"
      />
    </template>
  </Atable>
</template>

<script>

import Atable from '@/components/Table/Atable';
import BtnUpload from '@/components/Upload/BtnUpload';
import businessApi from '@/api/business';

export default {
  props: {
    applyId: {
      type: String
    }
  },
  name: "Step2",
  components: {
    Atable,
    BtnUpload,
  },
  data() {
    return {
      fileList: []
    }
  },
  computed: {
    fileConfig() {
      return [
        {
          prop: 'ruleName',
          label: '提交材料名称',
          width: '380'
        },
        {
          prop: 'fileNum',
          label: '文件数量',
        },
        {
          prop: 'actions',
          label: '上传材料',
          slot: 'actions',
          width: '250'
        },
      ];
    }
  },
  mounted() {
    this.getAttachments();
  },
  methods: {
    async getAttachments() {
      this.$emit('loading', true);
      await businessApi.getFileList({
        businessId: this.applyId,
        businessTable: 'StuffInfo'
      }).then(res => {
        // get all subType, and remove duplicate
        let subType = [...new Set(res.map(item => item.subType))];
        let attachments = subType.map(item => {
          return {
            stuffUniId: item,
            stuffName: [...new Set(res.filter(file => file.subType === item).map(file => file.description))].join(','),
          }
        });
        this.fileList = attachments.map(item => {
          return {
            ruleName: item.stuffName,
            fileNum: res.filter(file => file.subType === item.stuffUniId).length,
            file: res.filter(file => file.subType === item.stuffUniId)
          }
        });

        this.$store.commit('user/setAttachments', attachments);
      }).finally(() => {
        this.$emit('loading', false);
      }).catch(err => {
        this.$message.error(err.message);
        this.$store.commit('user/setAttachments', []);
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.down {
  color: #3c8cf1;
  cursor: pointer;
}
.btn-upload {
  align-items: center;
}
</style>
